/** * Created by Jackie on 2016/11/16.
 *  */
import Vue from 'vue'

import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import fastclick from 'fastclick'

import {sync} from 'vuex-router-sync'

import Device from './plugins/device'

import store from './vuex/store'
import App from './App'
import routerMap from './router-map'
// import filter from './filter/filter'

/* Click Event Bind */
/* global window:true*/
/* eslint no-undef: "error"*/
fastclick.attach(window.document.body)

/* Init Vue Filter */
// filter()

/* Install plus-in */
Vue.use(VueResource)
Vue.use(VueRouter)

Vue.use(Device)

/* Vue Resource Config */
/*
 * web server can't handle requests encoded as application/json
 * send the request as application/x-www-form-urlencoded MIME type
 * */
Vue.http.options.emulateJSON = true

/*
 * web server can't handle REST/HTTP requests like PUT, PATCH and DELETE
 * use a normal POST request
 * */
Vue.http.options.emulateHTTP = true

/* Router Config */
const router = new VueRouter()

router.map(routerMap)

let history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
/**
 * sync router loading status
 */
const commit = store.commit || store.dispatch
router.beforeEach(({to, from, next}) => {

    const toIndex = history.getItem(to.path)
    const fromIndex = history.getItem(from.path)
    if (fromIndex) {
        if (toIndex) {
            if (toIndex > fromIndex) {
                commit('UPDATE_DIRECTION', 'forward')
            } else {
                commit('UPDATE_DIRECTION', 'reverse')
            }
        } else {
            ++historyCount
            history.setItem('count', historyCount)
            to.path !== '/' && history.setItem(to.path, historyCount)
            commit('UPDATE_DIRECTION', 'forward')
        }
    } else {
        commit('UPDATE_DIRECTION', '')
    }

    commit('UPDATE_LOADING', true)
    setTimeout(next, 50)
})
router.afterEach(() => {
    commit('UPDATE_LOADING', false)
})

sync(store, router)

router.start(App, '#app')
